package com.santiao.youxiang.ui.fragment

import android.annotation.SuppressLint
import android.os.Build
import android.util.Log
import androidx.annotation.RequiresApi
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.santiao.youxiang.bean.EmailBean
import com.santiao.youxiang.bean.PostBean
import com.santiao.youxiang.bean.Weekly

//import com.lazyliuzy.commonui.utils.dj.GetHttpDataUtil.getfoodbyseek

//import com.lazyliuzy.entity.FoodSearchRes


import com.santiao.youxiang.bean.YibaoBean
import com.santiao.youxiang.bean.habitBillBean
import com.santiao.youxiang.bean.habitTimeLineBean
import com.santiao.youxiang.database.habitBill
import com.santiao.youxiang.database.habitTimeLine
//import com.santiao.youxiang.database.Bill
import com.santiao.youxiang.database.yibaoBill
import kotlinx.coroutines.launch
import org.litepal.LitePal
import java.time.LocalDateTime
import java.time.format.DateTimeFormatter
import java.util.Calendar
import kotlin.jvm.java

class HomeViewModel : ViewModel() {
val postList=MutableLiveData<MutableList<PostBean>>()
    val currentPost=MutableLiveData<Long>()
    val emailList=MutableLiveData<MutableList<EmailBean>>()//主页使用
    val emailList2=MutableLiveData<MutableList<EmailBean>>()
    val currentPostType=MutableLiveData<String>()//126 136 aliyun qq none
    val currentEmailType=MutableLiveData<Int>()//1收件箱 2已发送 3草稿箱 4垃圾邮件 5已删除 6病毒文件夹
/*    1 -> "INBOX"
    2 -> "INBOX" 已读
    3 -> "已发送"
    4 -> "草稿箱"
    5 -> "垃圾邮件"
    6 -> "已删除"*/
    val refreshEmail=MutableLiveData<Int>()
    val cleanHome=MutableLiveData<Boolean>()

    var yibaoData= MutableLiveData<List<YibaoBean>>()

    var lineData= MutableLiveData<List<habitTimeLineBean>>()
    var habitData= MutableLiveData<List<habitBillBean>>()

    object GlobalEventBus {
        private val _backEvent = MutableLiveData<String>()
        val backEvent: LiveData<String> = _backEvent

        fun postBackEvent(data: String) {
            _backEvent.postValue(data)
        }

        private val _switchEvent = MutableLiveData<String>()
        val switchEvent: LiveData<String> = _switchEvent

        fun postSwitchEvent(data: String) {
            _switchEvent.postValue(data)
        }

        private val _backControlEvent = MutableLiveData<String>()
        val backControlEvent: LiveData<String> = _backControlEvent

        fun postbackControlEvent(data: String) {
            _backControlEvent.postValue(data)
        }

    }

//    override fun addCloseable(closeable: Closeable) {
//        super.addCloseable(closeable)
//    }
//
//    override fun onCleared() {
//        super.onCleared()
//    }

//    GetHttpDataUtil.getfoodkind()
//    GetHttpDataUtil.getfoodbyseek("蛋类","","","1")



    @RequiresApi(Build.VERSION_CODES.O)
    fun getDBYibao(){

        viewModelScope.launch {
            try {
//                val result = getfoodkind2(/*type,cpName,id,page*/)
//                categoryData.value=result as List<foodCateBean>
                // 1. 先拿到当前年份（四位数），例如 “2025”
                val currentYear = Calendar.getInstance().get(Calendar.YEAR).toString()

// 2. 构造 like 模式：只匹配 “2025年…” 开头的 BillDate
                val pattern = "${currentYear}年%"

// 3. 用 LitePal 的 where + find，只查询符合条件的 yibaoBill
                val liveyi = LitePal
                    .where("BillDate LIKE ?", pattern)
                    .find(yibaoBill::class.java)
                Log.e("ViewModelResult", "Success: $liveyi")
                liveyi.get(0).id


                val homeYibaoBeans: List<YibaoBean> = liveyi.map { liveYibao ->
                    YibaoBean(
                        userId =liveYibao.userId ?:"" ,
                        id = liveYibao.id,
                        billType = liveYibao.billType,
                        billAmount = liveYibao.billAmount ?: " ",
                        BillDate = liveYibao.BillDate,
//                        token = liveYibao.token,
//                        last_token_time = liveYibao.last_token_time

                    )
                }

                yibaoData.value= homeYibaoBeans as List<YibaoBean>


                Log.e("ViewModelResult", "Success: $homeYibaoBeans")
            } catch (e: Exception) {

                Log.e("ViewModelResult", "Error: ${e.message}")
            }
        }
//         GetHttpDataUtil.getfoodbyseek(type,cpName,id,page) as List<FoodSearchRes>
    }

    /*fun getDBShebao(){

        viewModelScope.launch {
            try {

                // 1. 先拿到当前年份（四位数），例如 “2025”
                val currentYear = Calendar.getInstance().get(Calendar.YEAR).toString()

// 2. 构造 like 模式：只匹配 “2025年…” 开头的 BillDate
                val pattern = "${currentYear}年%"

// 3. 用 LitePal 的 where + find，只查询符合条件的 yibaoBill
                val liveshe = LitePal
                    .where("BillDate LIKE ?", pattern)
                    .find(shebaoBill::class.java)

//                val liveshe = LitePal.findAll(shebaoBill::class.java)

                Log.e("ViewModelResult", "Success: $liveshe")
//              var s=  liveshe.get(0).



                val homeShebaoBeans: List<YibaoBean> = liveshe.map { liveShebao ->
                    YibaoBean(
                        userId =liveShebao.userId ?:"" ,
                        id = liveShebao.id,
                        billType = liveShebao.billType,
                        billAmount = liveShebao.billAmount ?: " ",
                        BillDate = liveShebao.BillDate,
//                        token = liveYibao.token,
//                        last_token_time = liveYibao.last_token_time

                    )
                }

                shebaoData.value= homeShebaoBeans as List<YibaoBean>


                Log.e("ViewModelResult", "Success: $homeShebaoBeans")
            } catch (e: Exception) {

                Log.e("ViewModelResult", "Error: ${e.message}")
            }
        }
//         GetHttpDataUtil.getfoodbyseek(type,cpName,id,page) as List<FoodSearchRes>
    }*/


    @SuppressLint("NewApi")
    fun getDBLine(){

        viewModelScope.launch {
            try {



    /*            val livelines = LitePal.findAll(habitTimeLine::class.java)


                Log.e("ViewModelResult", "Success: $livelines")

                val homelineBeans: List<habitTimeLineBean> = livelines.map { liveline ->
                    habitTimeLineBean(
//                        userId =liveline.id ?:"" ,
                        id = liveline.id,
                        date = liveline.date,
                        detail = liveline.detail as ArrayList<habitTimeLineBean.Detail?>?,
//                        habitType = liveline.habitType,
//                        dateTime = liveline.dateTime,
//                        token = liveYibao.token,
//                        last_token_time = liveYibao.last_token_time

                    )
                }*/




                val livelines = LitePal.findAll(habitTimeLine::class.java)




                Log.e("ViewModelResult", "Success: $livelines")

                val homelineBeans: List<habitTimeLineBean> = livelines.map { liveline ->
                    // 手动查询每个 timeline 对应的 Detail 列表
                    val details: List<habitTimeLineBean.Detail> = liveline.getDetails().map { detail ->
                        habitTimeLineBean.Detail(
                            habitName = detail.habitName,
                            habitType = detail.habitType,
                            dateTime = detail.dateTime,
                            describe = detail.describe
                        )
                    }.reversed()

                    habitTimeLineBean(
                        id = liveline.id,
                        date = liveline.date,
                        detail = ArrayList(details) // 转成 ArrayList
                    )
                }.reversed()  // 对转换后的结果进行倒序




                /* val homelineBeans: List<habitTimeLineBean> = livelines.map { liveline ->
                     // 手动查询每个 timeline 对应的 Detail 列表
                     val details: List<habitTimeLineBean.Detail> = liveline.getDetails().map { detail ->
                         habitTimeLineBean.Detail(
                             habitName = detail.habitName,
                             habitType = detail.habitType,
                             dateTime = detail.dateTime,
                             describe = detail.describe
                         )
                     }

                     habitTimeLineBean(
                         id = liveline.id,
                         date = liveline.date,
                         detail = ArrayList(details) // 转成 ArrayList
                     )
                 }*/



                lineData.value= homelineBeans as List<habitTimeLineBean>


                Log.e("ViewModelResult", "Success: $homelineBeans")
            } catch (e: Exception) {

                Log.e("ViewModelResult", "Error: ${e.message}")
            }
        }
//         GetHttpDataUtil.getfoodbyseek(type,cpName,id,page) as List<FoodSearchRes>
    }


    @SuppressLint("NewApi")
    fun getDBHabit(){

        viewModelScope.launch {

            val current = LocalDateTime.now().toLocalDate()

            val year = current.year
            val monthValue = current.monthValue
            val dayOfMonth = current.dayOfMonth

//            val hour = current.hour
//            val minute = current.minute
//            val second = current.second

//            var updateTime="$year-$monthValue-$dayOfMonth $hour:$minute:$second"

            try {



                val livehabits = LitePal.findAll(habitBill::class.java)


                Log.e("ViewModelResult", "Success: $livehabits")

                val homehabitBeans: List<habitBillBean> = livehabits.map { livehabit ->
                    Log.e("getDBHabit:update ",livehabit.update.toString() )

                    val updateDateTimeStr = livehabit.update  // 获取 update 字段（字符串）

                    // 定义时间格式化器
                    val formatter = DateTimeFormatter.ofPattern("yyyy-M-d H:m:s")

                    // 解析 update 字段为 LocalDateTime 对象
                    val updateDateTime = LocalDateTime.parse(updateDateTimeStr, formatter)



                    // 提取 update 的日期部分
                    val updateDate = updateDateTime.toLocalDate()



                    // 比较当前日期和 update 的日期部分
                    if (updateDate.isBefore(current)) {
                        // 说明更新的日期已经过去了
//                        println("Data with update time: $updateDateTimeStr is from a previous date.")
                        livehabit.checkIns="0"
                        livehabit.todayFnish="0"
                        livehabit.save()
                    } else if (updateDate.isEqual(current)) {
                        // 说明更新日期是今天
//                        println("Data with update time: $updateDateTimeStr is from today.")
                    } else {
                        // 说明更新日期是未来的
//                        println("Data with update time: $updateDateTimeStr is from a future date.")
                    }

                    habitBillBean(
//                        userId =liveline.id ?:"" ,
                        id = livehabit.id,
                        habitName = livehabit.habitName,
                        habitToday_target = livehabit.habitToday_target ?: " ",
                        habitTargetDay = livehabit.habitTargetDay,
                        habitRemind = livehabit.habitRemind,
                        RemindTime = livehabit.RemindTime,
                        habitWeekly = livehabit.habitWeekly as ArrayList<Weekly?>?,
                        habithold_day = livehabit.habithold_day,
                        checkIns = livehabit.checkIns,
                        update = livehabit.update,
                        imageType = livehabit.imageType,
//                        token = livehabit.token,
//                        last_token_time = liveYibao.last_token_time

                    )
                }

                habitData.value= homehabitBeans


                Log.e("ViewModelResult", "Success: $homehabitBeans")
            } catch (e: Exception) {
//                ${e.message}
                Log.e("ViewModelResult", "Error: ${e.toString()}")
            }
        }
//         GetHttpDataUtil.getfoodbyseek(type,cpName,id,page) as List<FoodSearchRes>
    }



}